const UI = require('wy-UI');

var State = {
    Idle : 0,
    Request : 1,
    Runing :2,
    Reward : 3
}

cc.Class({
    extends: require('UI-PanelWindow'),

    properties: {

    },

    onLoad(){
        this._super();
        this.no_reward = cc.find('rewards',this.node);
        this.no_saibg = cc.find('saizibg',this.node)
        this.no_rewardResult = cc.find('RewardResult',this.node);
        this.tg_light = cc.find('light',this.node).getComponent('UI-Toggle');
        this.no_start = cc.find('chuantou/press',this.node);
        this.no_chuanTou = cc.find('chuantou',this.node);
        this.no_startEffect = cc.find('chuantou/pressEffect',this.node);
        this.no_startEffect.opacity = 0
        // this.no_start.on(cc.Node.EventType.TOUCH_END,this.onClickStart,this);
        this.no_build = cc.find('build',this.node);
        this.no_mask = cc.find('rewardMask',this.node)
        this.lb_power = cc.find('saizibg/nengliangbg/power',this.node).getComponent(cc.Label);
        this.lb_saizi = cc.find('saizibg/value',this.node).getComponent(cc.Label);
        this.tg_beishu = cc.find('beishu',this.node).getComponent('UI-Toggle');
        this.no_mask.active = false;
        this.b_isReady = false;
        this.o_rewardData = null;
        this.n_rewardIndex = 0;
        this.n_rewardRow = -1;
        this.n_result = 0 //抽奖的结束点
        this.node.on(cc.Node.EventType.TOUCH_MOVE,this.onTouch,this);

        this.s_state = State.Idle;

        this.endIndex = 48
        this.indexArr = [];
        for(var i=1; i<=this.endIndex; i++){
            this.indexArr[i] = i % 12;
        }
        var level = Math.floor(global.Data.store.civilizationLevel / 20);
        for(var j=0; j<11; j++){
            var item = global.DataConfig.lottery[level][j];
            var text = cc.find('item'+j+'/text',this.no_reward).getComponent(cc.Label);
            text.string = global.DataConfig.storage[item.id].name+' '+item.count;
        }
        this.showTime = 0;
        this.updatePower();
        global.Event.on('updateResource',this.updatePower.bind(this));

        var self = this;
        this.no_start.on(cc.Node.EventType.TOUCH_START,function(){
            self.no_startEffect.scale = 0.7;
            self.no_startEffect.opacity = 255
            self.no_startEffect.runAction(cc.spawn(cc.scaleTo(0.3,1.5,1.2),cc.fadeOut(0.3)))
        })
        
    },
    start(){
        var beishu = cc.sys.localStorage.getItem('_beishu');
        var b = parseInt(beishu)
        if(!b){
            b = 0;
        }
        this.tg_beishu.setToggle(b)
        this.tg_beishu.node.opacity = 0;
    },
    onDestroy(){
        global.Event.off('updateResource');
    },
    registerTouch(){
        this.node.on(cc.Node.EventType.TOUCH_MOVE,this.onTouch,this);
    },
    unRegisterTouch(){
        this.node.off(cc.Node.EventType.TOUCH_MOVE,this.onTouch,this);
    },

    onBtnBeiShu(event){
        cc.sys.localStorage.setItem('_beishu',event.toggle.index);
    },

    onTouch(event){
        var start = event.getStartLocation();
        var current = event.getLocation();
        if(current.x < start.x - 10){
            // global.GameLoop.toBuildLayer()
            this.onClickBuild();
        }
    },

    updatePower(){
        this.lb_power.string = global.Data.store.power;
    },

    onClickStart(){
        cc.log('onClickStart:',this.tg_beishu.getToggle()+1)
        
        var self = this;
        global.a_mutual = [];
        this.no_mask.active =true;
        this.httpGet('/game/gameuser','extract',{count:this.tg_beishu.getToggle()+1}, function(err,res){
            cc.log('res:',res)

            if(res && res[0]){
                self.b_isReady = false;
                self.o_rewardData = res;
                self.n_rewardIndex = 0;
                self.n_rewardRow = -1;
                for(var i=0; i<res.length; i++){
                    if(res[i].n == 10 || res[i].n == 6){
                        global.a_mutual.push(res[i].n)
                    }
                }
                global.Data.store.power -= 1;
                // self.updatePower();
                global.GameLoop.setMaskShow(true);
                self.startRound(res[0].n);
            } else {
                self.no_mask.active = false;
            }
        });
        // global.a_mutual=[6]
        // global.GameLoop.executeMutual();
    },

    itemExitCallFunc(){
        cc.log('itemExitCallFunc:');
    },

    onClickBuild(){
        global.GameLoop.toBuildLayer()
    },
    onBtnPet(){
        
        this.httpGet('/game/gameuser','pet.getPetMessage',{}, function(err,res){
            cc.log('res:',res);
            if(!err){
                if(res.pet.currentIndex == -1){
                    global.UI.ToolTip({message:'当前没有宠物'})
                    return;
                } else {
                    global.Data.PetData = res;
                    var pet = global.UIMgr.pushUI('UI/pet/PetLayer');
                    pet.getComponent('PetLayer').updateData();
                }
            }
        })

    },

    startRound(result){
        this.s_state = State.Runing;
        this.selectIndex = 0;

        this.indexArr.sort(function(a,b){
            return Math.random()-0.5;
        })
        this.n_result = result;
        this.showDelay = 0.05;
        this.showTime = 0;
        
    },
    getMutualArray(){
        return this.a_mutual;
    },

    rewardResult(index){
        this.n_rewardRow++;
        var data = this.o_rewardData[this.n_rewardIndex];
        var moveItem = false;
        
        if(data['award'] == null ? this.n_rewardRow >= 1 : (this.n_rewardRow >= 1 && data['award'].length <= this.n_rewardRow)){
            this.n_rewardIndex++;

            if(this.o_rewardData.length > this.n_rewardIndex){
                data = this.o_rewardData[this.n_rewardIndex];
            } else {
                cc.log('抽奖完成')
                // this.showItem(this.n_result)
                global.GameLoop.setMaskShow(false);
                this.state = State.Idle;
                global.GameLoop.executeMutual();
                return;
            }
            this.n_rewardRow = 0;
            moveItem = true
        }
        // this.showItem(data.n)
        var spriteFrame = null; //图片资源
        

        var item = cc.find('item'+data.n+'/icon',this.no_reward).getComponent(cc.Sprite);
        var startPos = item.node.convertToWorldSpace(cc.v2(item.node.width/2,item.node.height/2))//从哪个资源冒出来的

        var level = Math.floor(global.Data.store.civilizationLevel / 20);
        var names = ''
        if(this.n_rewardRow == 0){
            spriteFrame = item.spriteFrame;
            names = global.DataConfig.storage[data.n].name+' x ';
            names += global.DataConfig.lottery[level][data.n].count;
        } else if(this.n_rewardRow == 1){
            var award = data.award[this.n_rewardRow-1];
            spriteFrame = item.spriteFrame;
            names = global.DataConfig.storage[award.id].name+' x '+award.count;
        }
        var self = this
        function run(){
            self.no_mask.active = false;
            var node = global.EJMgr.pushUI('prefab/gameReady/RewardResult');
            var resultPanel = node.getComponent('RewardResult');
    
            var layer = global.GameLoop.getMenuBtnsLayer();
            var endpos = layer.getChildByName('pack').getPosition()
            var packPos = layer.convertToWorldSpace(endpos)
            resultPanel.setOptions({sf:spriteFrame,
                endPos:packPos,
                startPos:startPos,
                name:names,
                exitCB:self.rewardResult.bind(self)})

            if(self.n_rewardRow == 0){
                switch(data.n){
                    case 0:global.Data.store.power+= data['count']; break;
                    case 1:global.Data.store.water+= data['count']; break;
                    case 2:global.Data.store.corn += data['count']; break;
                    case 3:global.Data.store.fire += data['count']; break;
                    case 4:global.Data.store.mineral += data['count']; break;
                    case 5:global.Data.store.potato+= data['count']; break;
                    case 7:global.Data.store.soy+= data['count']; break;
                    case 8:global.Data.store.sorghum+= data['count']; break;
                    case 9:global.Data.store.wood += data['count']; break;
                }
            }

            if(self.n_rewardRow == 0){
                self.scheduleOnce(function(){
                    global.Event.emit('updateResource');
                    // global.GameLoop.updateHeadResources();
                },1)
            } else {
                
            }
        }
        if(moveItem){
            this.showItem(data.n)
            self.scheduleOnce(run,0.3)
            // setTimeout(run,300)
        } else {
            self.scheduleOnce(run,0.5)
            // run();
        }
    },

    update (dt) {
        if(this.s_state == State.Runing){
            this.showTime+=dt;
            if(this.showTime > this.showDelay){
                this.selectIndex += Math.floor(this.showTime / this.showDelay)
                if(this.selectIndex < this.endIndex){
                    this.showItem(this.indexArr[this.selectIndex])
                } else {
                    this.showItem(this.n_result)
                    this.rewardResult(this.n_result)
                    this.s_state = State.Idle;
                }
                this.tg_light.setToggle(this.selectIndex%2)
                this.showTime = 0;
            }
        } else {
            var last = Math.floor(this.showTime);
            this.showTime+=dt;
            var current = Math.floor(this.showTime);
            if(last != current){
                this.tg_light.setToggle(current%2)
            }
        }
        
    },
    showItem(itemId){ //1-11
        this.lb_saizi.string = itemId;
        var children = this.no_reward.children;
        for(var i=0; i<11; i++){
            var chd = children[i]
            if(chd.name == 'item'+itemId){
                chd.js.setToggle(2); 
            } else {
                chd.js.setToggle(1); 
            }
        }
    },

    onEnterMainScene(){
        this.stopActions();
        this.tg_light.node.runAction(cc.fadeIn(0.3));
        this.no_saibg.runAction(cc.spawn(cc.fadeIn(0.3),cc.moveTo(0.3,cc.v2(0,355)),cc.scaleTo(0.3,1.0)));
        this.no_reward.runAction(cc.spawn(cc.fadeIn(0.3),cc.moveTo(0.3,cc.v2(0,-30)),cc.scaleTo(0.3,1.0)));
        this.tg_light.node.runAction(cc.spawn(cc.fadeIn(0.3),cc.moveTo(0.3,cc.v2(0,-30)),cc.scaleTo(0.3,1.0)));
        this.no_build.runAction(cc.moveTo(0.3,cc.v2(260,-491)));
        this.no_chuanTou.y = -1100
        this.no_chuanTou.runAction(cc.sequence(cc.delayTime(0.3),cc.moveTo(0.2,cc.v2(0,-cc.winSize.height/2))));
        this.registerTouch();
        this.tg_beishu.node.active = true;
        this.tg_beishu.node.opacity = 0
        this.tg_beishu.node.runAction(cc.sequence(cc.delayTime(0.3),cc.fadeIn(0.1)));
    },
    onExitMainScene(){
        this.stopActions();
        this.no_saibg.runAction(cc.spawn(cc.moveTo(0.4,cc.v2(-415,-50+355)),cc.scaleTo(0.4,1.2),cc.fadeOut(0.4)).easing(cc.easeIn(0.4)))
        this.no_reward.runAction(cc.spawn(cc.moveTo(0.4,cc.v2(-415,-151)),cc.scaleTo(0.4,1.2),cc.fadeOut(0.4)).easing(cc.easeIn(0.4)))
        this.tg_light.node.runAction(cc.spawn(cc.moveTo(0.4,cc.v2(-415,-151)),cc.scaleTo(0.4,1.2),cc.fadeOut(0.4)).easing(cc.easeIn(0.4)))
        this.no_chuanTou.runAction(cc.sequence(cc.delayTime(0.1),cc.moveTo(0.15,cc.v2(0,-1100))));
        this.no_build.runAction(cc.sequence(cc.delayTime(0.1),cc.moveTo(0.15,cc.v2(460,-491))))
        this.unRegisterTouch();
        this.tg_beishu.node.active = false;
    },


    stopActions(){
        this.no_saibg.stopAllActions()
        this.no_reward.stopAllActions()
        this.tg_light.node.stopAllActions()
        this.no_chuanTou.stopAllActions()
        this.no_build.stopAllActions()
    },


    onEnterWindowBegin(){
        this.no_reward.scaleX = 0.7;
        this.no_reward.scaleY = 0.7;
        this.tg_light.node.scaleX = 0.7;
        this.tg_light.node.scaleY = 0.7;
        this.no_reward.runAction(cc.sequence(this.getEjectAction()));
        this.tg_light.node.runAction(cc.sequence(this.getEjectAction()));
        this.no_chuanTou.y = -1100
        this.no_chuanTou.runAction(cc.sequence(cc.delayTime(0.3),cc.moveTo(0.3,cc.v2(0,-cc.winSize.height/2)),cc.callFunc(this.onEnterWindowEnd.bind(this))));
        global.GameLoop.setMaskShow(true);
        this.tg_beishu.node.runAction(cc.sequence(cc.delayTime(0.3),cc.fadeIn(0.1)))
    },

    onEnterWindowEnd(){
        global.GameLoop.setMaskShow(false);
        if(global.Data.sysNotices.length){
            global.EJMgr.pushUI('UI/noticeLayer/NoticeLayer')
        }
    },

    onExitWindowBegin(){
        this._super();
        
    }


    
});
